﻿using Newtonsoft.Json;
using PMIS.Common.Dialog;
using PMIS.Controls;
using PMIS.HttpRequest;
using PMIS.Shared.DTO;
using PMIS.Shared.Models;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace PMIS.ViewModels.Menu
{
    public class AddEditMenuViewModel : DialogViewModelBase
    {
        private readonly HttpService _httpService;

        private List<MenuDto> _allMenus;

        public AddEditMenuViewModel(HttpService httpService)
        {
            _httpService = httpService;

            this.Menu = new MenuDto();

            LoadSysMenus();
        }

        private MenuDto _menu;

        public MenuDto Menu
        {
            get
            {
                return _menu;
            }
            set
            {
                SetProperty(ref _menu, value);
            }
        }

        private ICommand _saveCommand;
        public ICommand SaveCommand
        {
            get
            {
                if (_saveCommand == null)
                {
                    _saveCommand = new DelegateCommand(OnSave);
                }
                return _saveCommand;
            }
        }

        private ICommand _cancelCommand;
        public ICommand CancelCommand
        {
            get
            {
                if (_cancelCommand == null)
                {
                    _cancelCommand = new DelegateCommand(OnCancel);
                }
                return _cancelCommand;
            }
        }

        private async void OnSave()
        {
            bool result = false;
            if (string.IsNullOrEmpty(this.Menu.Id))
            {
                result = await Add();
            }
            else
            {
                result = await Edit();
            }

            if (result)
            {
                CloseDialog(new DialogResult(ButtonResult.OK));
            }
            else
            {
                ToastManager.ShowToast("保存失败");
            }
        }

        private async Task<bool> Add()
        {
            if (_selectedMenuItem != null)
            {
                _menu.ParentId = _selectedMenuItem?.Id;
            }
            var response = await _httpService.PostAsync(Api.MENU_ADD, _menu);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private async Task<bool> Edit()
        {
            if (_selectedMenuItem != null)
            {
                _menu.ParentId = _selectedMenuItem?.Id;
            }
            var response = await _httpService.PutAsync(Api.MENU_UPDATE, _menu);
            if (response?.code == 1)
            {
                long r = (long)response.data;
                return r == 1;
            }
            return false;
        }

        private void OnCancel()
        {
            CloseDialog(new DialogResult(ButtonResult.Cancel));
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            if (parameters.Count > 0)
            {
                this.Title = "编辑菜单";
                this.Menu = parameters.GetValue<MenuDto>("data");
            }
            else
            {
                this.Title = "新建菜单";
            }
        }

        private async void LoadSysMenus()
        {
            var response = await _httpService.GetAsync(Api.MENU_GET_LIST);
            if (response?.code == 1)
            {
                var data = JsonConvert.DeserializeObject<PagingModel<MenuDto>>(JsonConvert.SerializeObject(response.data));
                _allMenus = data?.Items.Where(p => p.Type == 1 || p.Type == 2).OrderBy(p => p.Sort).ToList();

                if (!string.IsNullOrEmpty(this.Menu.ParentId))
                {
                    SelectedMenuItem = _allMenus.FirstOrDefault(x => x.Id == this.Menu.ParentId);
                }

                MenuItems = new ObservableCollection<MenuDto>(_allMenus.Where(x => x.ParentId == null));
                foreach (var item in MenuItems)
                {
                    LoadChildMenus(item);
                }
            }
        }

        public void LoadChildMenus(MenuDto menu)
        {
            menu.Children = _allMenus.Where(x => x.ParentId == menu.Id).ToList();
            foreach (var subitem in menu.Children)
            {
                // Recursive call
                LoadChildMenus(subitem);
            }
        }

        private ObservableCollection<MenuDto> _menuItems;
        public ObservableCollection<MenuDto> MenuItems
        {
            get => _menuItems;
            set
            {
                SetProperty(ref _menuItems, value);
            }
        }

        private MenuDto _selectedMenuItem;
        public MenuDto SelectedMenuItem
        {
            get => _selectedMenuItem;
            set
            {
                SetProperty(ref _selectedMenuItem, value);
            }
        }
    }
}
